import PageImpl from "$UI/wxsys/lib/base/pageImpl";
var app = getApp();
import taskBase from '$UI/pcx/taskBase.js';
export default class IndexPage extends PageImpl {
    constructor(...args) {/*{{{*/this.comp = require("_comp").default; this._e = require("_event_").default;/*为代码提示动态插入的辅助代码,不要删除}}}*/
        super(...args);
        this.taskBase = new taskBase(this);
        
    }

    // 页面加载完成
    onPageLoaded(event/*{{{*/ = this._e.page_loaded/*}}}*/) {
        const operate = this.params.operate
        const rowid = this.params.rowid
        const mainData = this.comp('mainData')
        if (operate == 'new') {
            mainData.newData()
            this.comp('uiStatusData').setValue('newTask', '1')
        } else {
            mainData.setFilter('f1', [{
                name: "fid",
                value: rowid,
                op: "eqb"
            }])
            mainData.refreshData({
                onSuccess: (data) => {
                    if (operate == 'view') {
                        this.comp('detailData').refreshData()
                    }
                    this.comp('splitData').refreshData()
                    this.comp('uiStatusData').setValue('taskProcess', mainData.getValue('taskProgress'))
                }
            })
        }
        this.comp('uiStatusData').setValue('viewMode', operate)
    }

    // 保存 任务发布
    onBtnCreateTaskOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {

        const mainData = this.comp('mainData')
        let rowState = mainData.getCurrentRowState()
        const uiStatusData = this.comp('uiStatusData')
        if (uiStatusData.getValue('newTask') == '1') {
            // 设置任务Id全路径
            mainData.setValue('taskFid', '/' + mainData.getValue('fid'))
        }

        let info = mainData.check();
        if (!info.valid) {
            this.hint(info.msg[0], 'warning', 3000)
            return
        }

        const splitData = this.comp('splitData')
        if (splitData.count() == 0) {
            this.hint('请添加分配任务', 'warning', 3000)
            return
        }
        info = splitData.check();
        if (!info.valid) {
            this.hint(info.msg[0], 'warning', 3000);
            return
        }

        let parentFid = this.comp('mainData').getValue('taskFid')

        let splitList = []
        let mainRow = Object.assign({}, mainData.getCurrentRow())
        mainRow.taskStatus = '1'

        // 添加主数据
        splitList.push(Object.assign({}, mainRow, { plannedDate: new Date(mainRow.plannedDate) }))

        // 添加任务处理人集合
        let mainTaskUsers = []
        let splitIds = splitData.getIDs()
        // 遍历多条分配任务
        splitIds.forEach(sid => {
            let row = splitData.getRowByID(sid)
            // 处理时间和taskFid全路径
            row.taskFid = parentFid + '/' + sid
            let tempRow = Object.assign({}, row)
            tempRow.plannedDate = new Date(tempRow.plannedDate)
            // 当选择了多个任务人时
            if (tempRow.taskUserId.split(',').length > 1) {
                let uids = tempRow.taskUserId.split(',')
                let ufids = tempRow.taskUserFId.split(',')
                let unames = tempRow.taskUserName.split(',')
                uids.forEach((taskuid, idx) => {
                    let tempId = idx > 0 ? justep.UUID.createUUID() : tempRow.fid
                    let simName = unames[idx]
                    if (mainTaskUsers.indexOf(simName) == -1) {
                        mainTaskUsers.push(simName)
                    }
                    splitList.push(Object.assign({}, tempRow, {
                        fid: tempId,
                        taskFid: parentFid + '/' + tempId,
                        taskStatus: '0',
                        taskUserId: taskuid,
                        taskUserFId: ufids[idx],
                        taskUserName: simName
                    }))
                })
            } else {
                // 单条新增数据
                splitList.push(tempRow)
                let simName = tempRow.taskUserName
                if (mainTaskUsers.indexOf(simName) == -1) {
                    mainTaskUsers.push(simName)
                }
            }
        })
        splitList.forEach(sitem => {
            delete sitem._recoredState
            delete sitem.operCol
        })
        // 主任务的多个处理人 2022-06-06
        splitList[0].taskUserName = mainTaskUsers.join(',')
        wx.showLoading({
            title: '正在发布任务...'
        })
        this.comp('taskSaveUpdate').send({
            tasks: splitList
        }).then((res) => {
            wx.hideLoading()
            if (res.data) {
                let result = res.data
                if (result.state == 1) {

                    this.hint('发布任务成功', 'success', 2000)
                    // 逐个发送不同的任务通知
                    splitList.forEach(sitem => {
                        if (sitem.taskUserId && sitem.taskFid) {
                            this.taskBase.sendMsg(sitem.taskUserId, sitem.taskFid, sitem.taskName, sitem.taskUserName)
                        }
                    })

                    setTimeout(() => {
                        this.comp('commonOperation').okclose(this.comp('mainData'))
                    }, 500)
                } else {
                    this.hint('发布任务失败，' + result.msg, 'warning', 3000)
                }
            }
        }, (err) => {
            wx.hideLoading()
            this.hint('发布任务失败，请稍后重试', 'warning', 3000)
        })
    }

    // 校验添加任务明细按钮
    checkAddDetailBtn() {
        const mainData = this.comp('mainData')
        let info = mainData.check();
        if (!info.valid) {
            this.hint('任务概况中的' + info.msg[0], 'warning', 3000)
            return false
        }
        return true
    }

    // 分配任务
    onBtnSplitOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {
        if (this.checkAddDetailBtn()) {
            let rowState = this.comp('mainData').getCurrentRowState()
            this.newDateByType('splitData', '121')
        }
    }

    // 任务分配取消
    onBtnCancelOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {
        this.comp('drawer').close()

    }

    // 任务分配删除
    onBtnDelSplitOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {
        let row = event.context.$item
        if (row.taskStatus == '0') {
            this.comp('splitData').deleteData(row)
        } else {
            this.hint('仅能删除未开始的任务！')
        }
    }

    // 工作明细打开
    onBtnAddDetailOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {
        const dtData = this.comp('detailData')
        this.newDateByType('detailData', '111')
    }

    // 工作明细保存
    onBtnSaveDetailOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {
        let row = event.context.$item
        this.comp('detailData').to(row)
        this.comp('detailData').saveData({
            onSuccess: (data) => {
                this.hint('保存工作明细成功！', 'success', 2000)
                setTimeout(() => {
                    this.comp('detailData').refreshData()
                }, 100)
            }
        })
    }

    onBtnOkOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {
        this.isNew = false
        this.comp('drawerDetail').close()
    }

    // 工作明细取消
    onBtnCancelDetailOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {
        this.comp('drawerDetail').close()
    }

    // 打开抽屉并新建
    newDateByType(detailName = 'splitData', drawerName = 'drawer') {
        const splitData = this.comp(detailName)
        splitData.newData({
            onSuccess: (data) => {
                splitData.to(data.data[0])
                setTimeout(() => {
                    this.isNew = true
                    if (this.comp(drawerName)) {
                        this.comp(drawerName).open()
                        document.getElementById(drawerName).style.zIndex = 1014
                    }
                }, 10)
            }
        })
    }

    // new add
    // 选择任务完成人
    onBtnUserPOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {
        this.taskBase.onOpenOrgDialog(true, 'ogn,dpt,psm', '选择任务完成人')
    }

    // 查看和发布 部门和人员信息
    onOrgDialogReceive(event/*{{{*/ = this._e.OrgDialog_receive/*}}}*/) {
        const self = this
        let rows = event.data
        let ids = '', names = '', fids = '';
        const len = rows.length
        if (len > 0) {
            self.taskUserList = []
            for (var i = 0; i < len; i++) {
                const id = rows[i].id, name = rows[i].name, fid = rows[i].fid
                self.taskUserList.push({
                    taskUserId: id,
                    taskUserFId: fid,
                    taskUserName: name
                })
                if (ids == '') {
                    ids = id;
                    names = name;
                    fids = fid;
                } else {
                    ids += ',' + id;
                    names += ',' + name;
                    fids += ',' + fid;
                }
            }
            let columnName = 'taskUser'
            const splitData = self.comp('splitData');
            splitData.setValue(columnName + 'Id', ids)
            splitData.setValue(columnName + 'FId', fids)
            splitData.setValue(columnName + 'Name', names)
        }
    }

    // 更新任务进度
    onBtnProcessOnClick(event/*{{{*/ = this._e.Button_onClick/*}}}*/) {
        let mainData = this.comp('mainData')
        mainData.setValue('taskProgress', this.comp('uiStatusData').getValue('taskProcess'))
        if (mainData.getValue('taskProgress')) {

            // 更新主任务状态
            let maintaskStatus = mainData.getValue('taskStatus')
            if (!maintaskStatus || maintaskStatus + '' == '0') {
                mainData.setValue('taskStatus', '1')
            }

            mainData.saveData({
                onSuccess: (data) => {
                    this.hint('更新任务进度成功！', 'success', 2000)
                }
            })
        }
    }

    // 重要程度字典
    onDictDataAfterRefresh(event/*{{{*/ = this._e.restData_afterRefresh/*}}}*/) {
        let degreeData = this.comp('degreeData')
        let dlist = []
        event.rows.forEach(row => {
            dlist.push({
                id: parseInt(row.dictcode),
                label: row.dictname
            })
        })
        degreeData.clear()
        degreeData.newData({
            defaultValues: dlist
        })
    }

    onWxContextInited(event/*{{{*/ = this._e.wxContext_inited/*}}}*/) {
        // this.hint('测试信息,当前上下文组件初始化完成', 'success', 5000)
    }

    // 任务明细打开，不校验
    onDrawerOpen(event/*{{{*/ = this._e.Drawer_open/*}}}*/) {
        this.comp('uiStatusData').setValue('openDetail', '1')
    }

    // 任务明细关闭，校验
    onDrawerClose(event/*{{{*/ = this._e.Drawer_close/*}}}*/) {
        this.comp('uiStatusData').setValue('openDetail', '0')
    }
}



const data = [
    { createdAt: '2024-11-21T10:00:00Z', updatedAt: '2024-11-21T12:00:00Z' },
    { createdAt: '2024-11-20T09:00:00Z', updatedAt: '2024-11-21T08:00:00Z' },  // 这里修改时间小于创建时间
    { createdAt: '2024-11-19T14:00:00Z', updatedAt: '2024-11-19T16:00:00Z' }
  ];

  let dtData = this.comp("billData")
  if (dtData.count() <= 0) {
      this.hint("请选择发票明细！", 'warning', 4000)
      return
  }
  let detailList = []
  if (dtData.count() > 0) {
      let idlist = dtData.getIDs()

      let isBreak = false;
      idlist.forEach(idstr => {
          let row = dtData.getRowByID(idstr)
          let ditem = Object.assign({}, row)

          delete ditem._recoredState
          delete ditem.sums
          detailList.push(ditem)
      })
      if (isBreak) {
          return
      }
      
  }
  